<template>
  <div class="flow">
    <!-- 员工信息卡片 -->
    <div class="formLook" :class="{ 'full-width': isFullWidth }">
      <TitleComponent title="调动申请" />

      <div class="Resignation">
        <div class="employee-card">
          <div class="employee-avatar">
            <ImageComponent
              :src="userInfoForm.personPhoto || ''"
              width="100px"
              height="100px"
              borderRadius="6px"
            />
          </div>

          <el-form label-width="100px" size="small">
            <div class="section-title" style="margin-left: 20px">
              <span>员工信息</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="员工账号：">
                  <span>{{ userInfoForm.applicantPersonName }}</span>

                  <el-button v-if="route.query.text == 'add'" @click="InfoClick"
                    >选择员工</el-button
                  >
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工号：">
                  <span>{{ userInfoForm.jobNumber }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系电话：">
                  <span>{{ userInfoForm.phoneNumber }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="工作邮箱：">
                  <span class="ellipsis-text">{{ userInfoForm.mail }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="岗位名称：">
                  <span>{{ userInfoForm.oldJobName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="岗位性质：">
                  <span>{{ userInfoForm.jobNature }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="部门：">
                  <span>{{ userInfoForm.oldDeptName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="职级：">
                  <span>{{ positionLevelText }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="直属领导：">
                  <span>{{ userInfoForm.directLeaderName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="最高领导：">
                  <span>{{ userInfoForm.supremeLeaderName }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="入职日期：">
                  <span>{{ userInfoForm.joinTime }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="转正日期：">
                  <span>{{ userInfoForm.becomePassTime }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <!-- 申请流程 -->
        <div class="application-form">
          <div style="align-items: center; padding: 15px 0">
            <span style="font-size: 16px; margin-left: 10px">申请流程</span>
            <el-divider></el-divider>
          </div>
          <el-form
            ref="formRef"
            :model="userInfoForm"
            :rules="rules"
            label-width="120px"
            style="margin-left: 20px"
          >
            <!-- 调岗信息 -->
            <div class="section-title">
              <span>调岗信息</span>
            </div>

            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="调岗类型：" prop="typeTransfer">
                  <span>{{
                    formatTypeTransfer(userInfoForm.typeTransfer)
                  }}</span>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="申请日期：" prop="applyDate">
                  <span>{{ userInfoForm.applyDate }}</span>
                </el-form-item>
              </el-col>
            </el-row>

            <div class="transfer-info-container">
              <div class="section-title">
                <span>调岗后岗位信息</span>
              </div>

              <el-row :gutter="20">
                <!-- <el-col :span="24">
                  <el-form-item label="岗位：" prop="position">
                    <div class="info">
                      <a class="original-info"></a>
                      <a class="arrow">→</a>
                      <a class="target-info">{{ userInfoForm.name }}</a>
                    </div>
                  </el-form-item>
                </el-col> -->

                <el-col :span="24">
                  <el-form-item label="岗位名称：" prop="jobName">
                    <div class="info">
                      <a class="original-info">{{ userInfoForm.oldJobName }}</a>
                      <a class="arrow">→</a>
                      <a class="target-info">{{
                        userInfoForm.newDepartmentJobName
                      }}</a>
                    </div>
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item label="部门：" prop="department">
                    <div class="info">
                      <a class="original-info">{{
                        userInfoForm.oldDeptName
                      }}</a>
                      <a class="arrow">→</a>
                      <a class="target-info">{{ userInfoForm.newJobName }}</a>
                    </div>
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item label="直属领导：" prop="directLeader">
                    <div class="info">
                      <a class="original-info">{{
                        userInfoForm.directLeaderName
                      }}</a>
                      <a class="arrow">→</a>
                      <a class="target-info">{{
                        userInfoForm.leaderAfterTransferName
                      }}</a>
                    </div>
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item label="最高领导：" prop="supremeLeader">
                    <div class="info">
                      <a class="original-info">{{
                        userInfoForm.supremeLeaderName
                      }}</a>
                      <a class="arrow">→</a>
                      <a class="target-info">{{
                        userInfoForm.leaderAfterHighName
                      }}</a>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <!-- 其他信息 -->
            <!-- <el-divider content-position="left">其他信息</el-divider> -->
            <div class="section-title">
              <span>其他信息</span>
            </div>
            <el-form-item label="调岗说明：" prop="reasonTransfer">
              <!-- <el-input
            v-model="userInfoForm.reasonTransfer"
            type="textarea"
            :maxlength="300"
            placeholder="请输入"
            show-word-limit
          ></el-input> -->
              <span>
                {{ userInfoForm.reasonTransfer }}
              </span>
            </el-form-item>

            <el-form-item label="其他附件：" prop="saveTransferFileVos">
              <attachment
                v-if="
                  userInfoForm.saveTransferFileVos &&
                  userInfoForm.saveTransferFileVos != null
                "
                :employeeResignFileVoList="userInfoForm.saveTransferFileVos"
              >
              </attachment>
              <!-- <Upload
              :modelValue="userInfoForm.saveTransferFileVos"
              :isShowTip="false"
              @update:modelValue="uploadFiles"
              @delete="handleFileDelete"
            ></Upload> -->
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="flowtab_info" v-if="isFullWidth">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="流程过程" name="流程过程">
          <div class="flowProcess">
            <steps
              :flowableDataList="flowableDataList"
              @submit="handleSubmit"
              @close="handleClose"
              v-bind="route.query.examine == 1 ? { flowableBtns } : {}"
            >
            </steps>
          </div>
        </el-tab-pane>
        <el-tab-pane label="流程图" name="流程图">
          <bpmnViewer :flowData="flowDatas" :id="hightlightId" />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- <ChooseSku ref="ChooseSkuRef" @select="handleSelect" />


    <NeedWorksDialog
      :needWorksDialog="openDialog"
      ref="openRef"
      @ok="handleOk"
      @cancel="handleCancel"
    >
    </NeedWorksDialog> -->

    <EmployeeDialog
      ref="employeeDialogRef"
      @update:selected="handleEmployeeSelected"
    />
    <!-- 岗位库选择 -->
    <PositionDialog
      ref="positionDialogRef"
      :department-options="buIdOptions"
      @confirm="handlePositionConfirm"
    />
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import ImageComponent from "@/components/ImageComponent.vue";
import { useRouter } from "vue-router";
import { formatDate } from "@/utils/index.js";

import Upload from "@/components/FileUpload/index.vue";
import TitleComponent from "@/components/TitleComponent.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import {
  transferInfo,
  transferInfoId,
  transferApi,
} from "@/api/employeeRelations/transferManagement.js";

import EmployeeDialog from "@/components/EmployeeDialog/index.vue";
import PositionDialog from "@/components/PositionDialog/index.vue";
import attachment from "@/components/attachment.vue";
import useUserStore from "@/store/modules/user.js";
import {
  flowableTodo,
  flowablePhoto,
  flowableRecord,
} from "@/api/flowableApi/flowableApi.js";
import bpmnViewer from "@/components/Process/viewer/index.vue";
import { seeFileView, getFileName } from "@/utils/fileView.js";
import steps from "@/components/step/index.vue";

const router = useRouter();

const user = useUserStore().user;
const userInfoForm = reactive({
  applicantPersonName: "", //员工账号
  jobNumber: "", //工号
  phoneNumber: "", //联系电话
  mail: "", //工作邮箱
  oldJobName: "", //原岗位名称
  oldDeptName: "", //原部门
  jobNature: "", //岗位性质
  positionLevel: "", //职级
  directLeaderName: "", //直属领导
  supremeLeaderName: "", //最高领导
  joinTime: "", // 入职日期
  becomePassTime: "", //转正日期
  typeTransfer: "", //调岗类型
  applyDate: "", //申请日期

  newDepartmentJobName: "", //调岗后岗位名称
  nowJobNature: "", //调岗后岗位性质
  newJobName: "", //调岗后部门
  nowPositionLevel: "", //调岗后职级
  leaderAfterTransferName: "", //调岗后直属领导
  leaderAfterHighName: "", //调岗后最高领导
  reasonTransfer: "", //调岗说明
  saveTransferFileVos: [], //附件
});

const rules = reactive({
  typeTransfer: [
    { required: true, message: "请选择调岗类型", trigger: "change" },
  ],
  applyDate: [{ required: true, message: "请选择申请日期", trigger: "change" }],
  newDepartmentJobName: [
    { required: true, message: "请选择调入岗位", trigger: "blur" },
  ],
  reasonTransfer: [
    { required: true, message: "请输入调岗说明", trigger: "blur" },
  ],
});

const formRef = ref(null);
const route = useRoute();
const { proxy } = getCurrentInstance();

const activeName = ref("流程过程");

// 岗位信息库弹窗
const openDialog = ref(false);
const ChooseSkuRef = ref(null);
const flowDatas = ref({});
// 留痕数据
const flowableDataList = ref([]);
// 审核按钮
const flowableBtns = ref([]);
// 下一个审批数据
const flowableTodoData = ref([]);
const procInsId = ref("");
// 高亮节点id
const hightlightId = ref("");
const taskId = ref("");

const query = computed(() => {
  let id = route.query ? Number(route.query.id) : "";
  return { id };
});
onMounted(() => {
  getDetails();
});
const isFullWidth = computed(() => {
  return route.query.workFlow === "1";
});
function getDetails() {
  transferInfo(route.query.id).then((res) => {
    if (res.data) {
      Object.keys(res.data).forEach((item) => {
        if (res.data[item]) {
          userInfoForm[item] = res.data[item];
          userInfoForm.typeTransfer = res.data.typeTransfer;
          userInfoForm.directLeaderName = res.data.directLeaderName;
          userInfoForm.oldDeptName = res.data.oldDeptName;

          userInfoForm.joinTime = formatDate(res.data.joinTime).dates;
          userInfoForm.becomePassTime = formatDate(
            res.data.becomePassTime
          ).dates;
          userInfoForm.applyDate = formatDate(res.data.applyDate).dates;
        }
        userInfoForm.newDepartmentJobName = res.data.newDeptName;
      });

      if (res.data.processId) {
        procInsId.value = res.data.processId;
        init(res.data.processId);
      }
    }
  });
}

function handleEmployeeSelected(item) {
  console.log(item, "选中的值");
  console.log(item[0]);
  // selectedItem.value = item; // 更新选中的项
  let params = {
    id: item[0],
  };
  transferInfoId(params).then((res) => {
    console.log(res, "调岗信息");
    if (res.data) {
      Object.keys(res.data).forEach((item) => {
        if (res.data[item]) {
          userInfoForm[item] = res.data[item];
        }
      });
    }
    // userInfoForm.newDepartmentJobName = res.data.newDepartmentJobName;
    // userInfoForm.nowJobNature = res.data.nowJobNature;
  });
}

const handleClose = () => {
  router.go(-1);
};

const init = async (processId) => {
  /**
   *  processId 流程实例id
      owner 指定人id
      role候选人id
      flowKey 流程key
   */
  let params = {
    owner: user.userId,
    role: user.userId,
    flowKey: "jobtrasfer",
  };

  try {
    // 留痕
    const recordRes = await flowableRecord({
      procInsId: processId,
      flowKey: "jobtrasfer", // 后面需修改为调动的flowKey
    });
    if (recordRes.data.flowList.length > 0) {
      recordRes.data.flowList.sort((a, b) => {
        return Number(b.taskId) - Number(a.taskId) < 0;
      });
      flowableDataList.value = recordRes.data.flowList;
      console.log(flowableDataList.value, "flowableDataList.value");
      if (flowableDataList.value.length > 0) {
        nextTick(() => {
          let x = document.querySelectorAll(".el-step__icon-inner");
          x.forEach((item, index) => {
            item.innerHTML = x.length - index;
          });
        });
      }
    }
    console.log(processId, "processIdprocessIdprocessId");
    // 流程审批按钮
    const todoRes = await flowableTodo(processId, params);

    console.log(todoRes, "todoRestodoRes");
    if (todoRes.data.length > 0) {
      // 审批
      flowableBtns.value = JSON.parse(todoRes.data[0].description)[0].btns;

      flowableTodoData.value = todoRes.data[0];
      taskId.value = todoRes.data[0].taskId;
    }
  } catch (error) {
    console.error(error);
  }
};

// 选择岗位
const handlePositionConfirm = (selectValue) => {
  console.log(selectValue, "selectValue");

  if (selectValue.value.length === 0) {
    ElMessage({
      type: "warning",
      message: "请选择至少一个岗位",
    });
    return;
  }

  // 新增下清空现有的标签页和数据
  if (route.query.edit != "1") {
    // editableTabs.value = [];
    // neekWorksForm.jobPostDetailDtoList = {};
  }

  selectValue.value.forEach((selectedItem, index) => {
    console.log(selectedItem, "selectedItem");
    //新对象
    const selectedJob = Object.assign({}, selectedItem);

    console.log(selectedJob, "selectedJob");
    userInfoForm.newDepartmentJobName = selectedJob.jobName;
    userInfoForm.nowPositionLevel = selectedJob.qualification;
  });
  openDialog.value = false;
};
const submit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success("提交成功");
    } else {
      ElMessage.error("请填写必填项");
      return false;
    }
  });
};

const positionLevelText = computed(() => {
  const positionLevelMap = {
    0: "初级",
    1: "中级",
    2: "高级",
  };
  return positionLevelMap[userInfoForm.positionLevel] || "";
});
const InfoClick = () => {
  ChooseSkuRef.value.open((value) => {
    console.log(value);
    console.log(item.id);
  });
};

const uploadFiles = (files) => {
  userInfoForm.saveTransferFileVos = files;
};

const handleFileDelete = (updatedFiles) => {
  userInfoForm.saveTransferFileVos = updatedFiles;
};
const handleClick = (tab) => {
  if (tab.props.name == "流程图") {
    flowablePhoto({
      procInsId: procInsId.value,
      flowKey: "jobtrasfer", // 后续需修改为调动管理flowKey
    }).then((res) => {
      flowDatas.value = res.data;
      hightlightId.value = res.data.nodeData[res.data.nodeData.length - 1].key;
    });
  }
};
const formatTypeTransfer = (type) => {
  const typeMap = {
    0: "社会招聘",
    1: "应届生",
    2: "实习生",
  };
  return typeMap[type] || "";
};

const handleSubmit = (parameter) => {
  let item = parameter.type;
  let comment = parameter.comment;
  // 参数
  let data = {
    accessory: [],
    accessoryList: [],
    agencyId: item.agencyId ? item.agencyId : "",
    agencyNextrole: "",
    // 当前人
    assignee: user.userId,
    // 审批意见
    auditOpinion: comment,
    // 当前时间
    auditTime: formatDate(new Date()).allDate,
    // 审批人 userName
    auditUserName: user.userName,
    beAssigner: "",
    beAssignerName: "",
    beAssignerRole: "",
    // 按钮名
    btnName: item.btnName,
    // user buid
    buId: user.dept.deptId,
    // 按钮id
    id: query.value.id,
    messageId: "",
    nextBuCode: "",
    otherFiles: [],
    processInstanceId: flowableTodoData.value.processInstanceId,
    status: item.status,
    taskId: flowableTodoData.value.taskId,
    // 按钮 vars
    vars: item.btnValue ? item.btnValue : "",
    flowKey: "RECRUIT_DEMAND",
  };
  if (item.btnName == "保存") {
    console.log(data, "保存的data");
    console.log(item, "保存的item");
    approveGoto(data, item);
  } else {
    ElMessageBox.confirm(`是否要${item.btnName}这条用人需求申请审批?`, "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        approveGoto(data, item);
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "已取消",
        });
      });
  }
};

const approveGoto = (data, item) => {
  transferApi(data, item.btnUrl).then((res) => {
    if (res.code == 200) {
      ElMessage.success(`${item.btnName}成功`);
      handleClose();
    } else {
      ElMessage.error(`${item.btnName}失败`);
    }
  });
};
</script>

<style scoped lang="scss">
.container {
  margin: 0 auto;
}

.Resignation {
  background: #f1f1f1;
  border-radius: 11px;
}
.back-button {
  margin-bottom: 20px;
}

.employee-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 0px 0 rgba(0, 0, 0, 0.1);
  // padding: 10px;
  margin-bottom: 10px;
}

.application-form {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 1px 0px;
  // height: 100%;
}

.el-divider--horizontal {
  margin: 15px 0;
}

.button-group {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: bold;
  color: #606266;
}

:deep(.el-textarea__inner) {
  resize: none;
}

.section-title {
  font-size: 15px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 0px solid #409eff;
  color: #16191d;
}
.position-container {
  display: flex;
}

.contianer-left {
  width: 48%;
}
.contianer-right {
  width: 48%;
}

.transfer-info-container {
  margin-top: 20px;
}

.section-title {
  font-weight: bold;
  margin: 20px 0 15px 0;
  padding-left: 15px;
  position: relative;
}

.section-title:before {
  content: "";
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 4px;
  background-color: #409eff;
  border-radius: 2px;
}

.el-form-item {
  margin-bottom: 15px;
}

.original-info {
  min-width: 180px;
  color: #606266;
}

.arrow {
  margin: 0 10px;
  color: #409eff;
}

.target-info {
  display: flex;
  color: #409eff;
}
span {
  width: 80%; /* 设定容器的宽度 */

  white-space: normal; /* 允许文本换行 */
}

.info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
</style>
